<template>
  <div class="pages">
    <!-- 头部导航 -->
    <div class="header">
      <button class="back-button fff" @click="router.back()">
        <span class="back-icon">←</span>
      </button>
      <span class="header-title fff">自行上传</span>
    </div>

    <div class="choose-page">
      <div class="choose-title">从本地上传录音</div>
      <div style="height: 19px;"></div>
      <div class="choose-tips">
        <div class="left">小贴士</div>
        <div class="right">请上传一段3-10秒的清晰语音(.wav格式)发音标准、无杂音，建议情感表达丰富</div>
      </div>
      <div class="upload-file-block" @click="triggerFileInput">
        <div class="upload-content">
          <!-- <img src="@/assets/images/config/sound/addSound.png" alt="上传" class="upload-icon"> -->
          <div class="upload-text">添加音频</div>
          <div class="upload-hint">支持 mp3, wav 格式</div>
        </div>
        <input 
          ref="fileInput" 
          type="file" 
          id="upload-file-input" 
          accept="audio/mpeg, audio/wav"
          style="display: none"
          @change="handleFileSelect"
        >
      </div>
      
      <!-- 上传进度显示 -->
      <div v-if="uploadProgress > 0 && uploadProgress < 100" class="progress-area">
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
        </div>
        <div class="progress-text">上传中... {{ uploadProgress }}%</div>
      </div>
      
      <!-- 上传状态提示 -->
      <div v-if="uploadStatus" class="status-message" :class="{ success: uploadStatus.includes('成功'), error: uploadStatus.includes('失败') }">
        {{ uploadStatus }}
      </div>
      
      <!-- 上传成功的音频列表 -->
      <div v-if="uploadedAudios.length > 0" class="audio-list">
        <div class="list-title">已上传音频</div>
        <div class="audio-items">
          <div
            v-for="audio in uploadedAudios"
            :key="audio.id"
            class="audio-item"
            :class="{ active: playingAudioId === audio.id }"
            @click="playAudio(audio)"
          >
            <div class="audio-info">
              <div class="audio-name">{{ audio.name }}</div>
              <div class="audio-size">{{ formatFileSize(audio.size) }}</div>
            </div>
            <div class="audio-status">
              {{ playingAudioId === audio.id ? '播放中...' : '点击播放' }}
            </div>
          </div>
        </div>
      </div>
      
      <div style="height: 75px;"></div>
      <div class="btn-block">
        <button class="live-btn" @click="router.back(); store.configTabId = 2">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from '@/stores/data'

const store = useStore()
const router = useRouter()
const fileInput = ref<HTMLInputElement>()
const uploadProgress = ref(0)
const uploadStatus = ref('')
const uploadedAudios = ref<Array<{id: number, name: string, size: number, url: string}>>([])
const playingAudioId = ref<number | null>(null)
const audioPlayer = new Audio()

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 处理文件选择
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (!target.files || target.files.length === 0) return
  
  const file = target.files[0]
  uploadFile(file)
}

// 上传文件到服务器
async function uploadFile(file: File) {
  uploadProgress.value = 0
  uploadStatus.value = ''

  // 验证文件类型
  const validExt = ['.mp3', '.wav']
  const ext = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
  if (!validExt.includes(ext)) {
    uploadStatus.value = '只允许上传 mp3 或 wav 格式'
    setTimeout(() => { uploadStatus.value = '' }, 3000)
    return
  }

  // 验证文件大小（10MB）
  if (file.size > 10 * 1024 * 1024) {
    uploadStatus.value = '文件大小不能超过10MB'
    setTimeout(() => { uploadStatus.value = '' }, 3000)
    return
  }

  const formData = new FormData()
  formData.append('file', file)

  try {
    // 使用 XMLHttpRequest 来获取上传进度
    const xhr = new XMLHttpRequest()
    
    // 监听上传进度
    xhr.upload.addEventListener('progress', (event) => {
      if (event.lengthComputable) {
        const percentComplete = (event.loaded / event.total) * 100
        uploadProgress.value = Math.round(percentComplete)
      }
    })
    
    // 监听请求完成
    xhr.addEventListener('load', () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        const responseText = JSON.parse(xhr.responseText)
        uploadStatus.value = '上传成功'
        localStorage.setItem("muc", responseText.exists[0])
        // 添加上传成功的音频到列表
        // const audioUrl = `http://${store.runningData.ip}:1352/audio/${file.name}`
        const audioUrl = `http://${store.runningData.ip}:1352${responseText.open_urls[0]}`
        uploadedAudios.value.unshift({
          id: Date.now(),
          name: file.name,
          size: file.size,
          url: audioUrl
        })
        // 3秒后清除状态
        setTimeout(() => {
          uploadStatus.value = ''
          uploadProgress.value = 0
        }, 3000)
      } else {
        throw new Error(`HTTP ${xhr.status}`)
      }
    })
    
    // 监听错误
    xhr.addEventListener('error', () => {
      throw new Error('网络错误，请检查网络连接')
    })
    
    // 发送请求
    xhr.open('POST', `http://${store.runningData.ip}:1352/upload-model`)
    xhr.send(formData)
    
  } catch (err) {
    console.error('上传失败:', err)
    uploadStatus.value = '上传失败：' + (err as Error).message
    uploadProgress.value = 0
    setTimeout(() => { uploadStatus.value = '' }, 3000)
  } finally {
    // 清空文件输入
    if (fileInput.value) {
      fileInput.value.value = ''
    }
  }
}

// 播放音频
const playAudio = async (audio: {id: number, url: string}) => {
  console.log("playAudio", audio)
  try {
    // 停止当前播放的音频
    if (playingAudioId.value) {
      audioPlayer.pause()
      audioPlayer.currentTime = 0
    }
    
    // 设置新的音频源并播放
    audioPlayer.src = audio.url
    playingAudioId.value = audio.id
    
    await audioPlayer.play()
    
    // 监听播放结束
    audioPlayer.onended = () => {
      playingAudioId.value = null
    }
    
    // 监听播放错误
    audioPlayer.onerror = () => {
      playingAudioId.value = null
      uploadStatus.value = '播放失败，请检查音频文件'
      setTimeout(() => { uploadStatus.value = '' }, 3000)
    }
    
  } catch (err) {
    console.error('播放失败:', err)
    playingAudioId.value = null
    uploadStatus.value = '播放失败：' + (err as Error).message
    setTimeout(() => { uploadStatus.value = '' }, 3000)
  }
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

onMounted(() => {
  // 初始化代码
})

// 组件卸载时停止播放
onUnmounted(() => {
  if (playingAudioId.value) {
    audioPlayer.pause()
    audioPlayer.currentTime = 0
  }
})

</script>

<style lang="scss" scoped>
.pages {
  box-sizing: border-box;
  background: #006CFF;
  overflow: hidden;
}

/* 顶部 header（若在别处已定义，可删） */
.header {
  display: flex; align-items: center; gap: 8px;
  padding: 12px 16px;
}
.header-title { font-weight: 600; }

.choose-page {
  padding: 22px 16px;
  box-sizing: border-box;
  width: 100%;
  border-radius: 20px 20px 0 0;
  background: #ffffff;
  flex: 1;
  overflow-y: auto;

  .choose-tips {
    display: flex;
    margin-bottom: 38px;
    .left {
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 10px;
      color: #006CFF;
      height: 20px;
      background: #E4F2FD;
      margin-right: 11px;
      border-radius: 4px;
      padding: 0 3px;
      box-sizing: border-box;
      line-height: 20px;
    }
    .right {
      flex: 1;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #595959;
      line-height: 20px;
    }
  }
  .upload-file-block {
    background: url(@/assets/images/config/sound/addSound.png);
    width: 398px;
    height: 80px;
    padding-bottom: 35px;
    padding-top: 5px;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .upload-content {
      text-align: center;
      
      .upload-icon {
        width: 40px;
        height: 40px;
        margin-bottom: 8px;
      }
      
      .upload-text {
        font-family: PingFang SC;
        font-weight: 600;
        font-size: 16px;
        color: #006CFF;
        margin-bottom: 4px;
      }
      
      .upload-hint {
        font-family: PingFang SC;
        font-weight: 400;
        font-size: 12px;
        color: #999999;
      }
    }
  }
  
  .progress-area {
    margin-top: 16px;
    padding: 12px;
    background: #F6FAFF;
    border-radius: 8px;
    
    .progress-bar {
      width: 100%;
      height: 6px;
      background: #E0E0E0;
      border-radius: 3px;
      overflow: hidden;
      margin-bottom: 8px;
      
      .progress-fill {
        height: 100%;
        background: #006CFF;
        transition: width 0.3s ease;
      }
    }
    
    .progress-text {
      font-family: PingFang SC;
      font-weight: 400;
      font-size: 12px;
      color: #666666;
      text-align: center;
    }
  }
  
  .status-message {
    margin-top: 12px;
    padding: 8px 12px;
    border-radius: 4px;
    font-family: PingFang SC;
    font-weight: 500;
    font-size: 14px;
    text-align: center;
    
    &.success {
      background: #E8F5E8;
      color: #4CAF50;
      border: 1px solid #4CAF50;
    }
    
    &.error {
      background: #FFEBEE;
      color: #F44336;
      border: 1px solid #F44336;
    }
  }
  
  .audio-list {
    margin-top: 20px;
    background: #FFFFFF;
    border-radius: 12px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .list-title {
      font-family: PingFang SC;
      font-weight: 600;
      font-size: 16px;
      color: #00042D;
      margin-bottom: 12px;
    }
    
    .audio-items {
      .audio-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px;
        border: 1px solid #F0F0F0;
        border-radius: 8px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover, &.active {
          border-color: #006CFF;
          background: #F0F7FF;
        }
        
        .audio-info {
          flex: 1;
          
          .audio-name {
            font-family: PingFang SC;
            font-weight: 500;
            font-size: 14px;
            color: #00042D;
            margin-bottom: 4px;
            word-wrap: break-word;
            word-break: break-all;
          }
          
          .audio-size {
            font-family: PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #999999;
          }
        }
        
        .audio-status {
          font-family: PingFang SC;
          font-weight: 500;
          font-size: 12px;
          color: #006CFF;
          padding: 4px 8px;
          background: rgba(0, 108, 255, 0.1);
          border-radius: 4px;
        }
      }
    }
  }

  .choose-title {
    font-family: PingFang SC, PingFang SC;
    font-weight: 600;
    font-size: 20px;
    color: #1A1A1A;
  }

  .choose-sound-list {
    display: flex;
    flex-direction: column;
    gap: 10px;

    .item {
      position: relative;
      padding: 12px 14px;
      border-radius: 10px;
      border: 1px solid #E9E9E9;
      cursor: pointer;
      transition: all .15s ease;

      .text {
        font-size: 14px;
        color: #333;
      }

      &:hover {
        border-color: #B6D7FF;
        box-shadow: 0 2px 8px rgba(0, 108, 255, 0.08);
      }
    }

    .item.active {
      background: linear-gradient(90deg, #E9F3FF 0%, #F2F8FF 100%);
      border-color: #006CFF;
      .text { color: #006CFF; font-weight: 600; }
    }

    .playing-badge {
      position: absolute;
      right: 10px;
      top: 10px;
      font-size: 12px;
      color: #006CFF;
      padding: 2px 8px;
      background: rgba(0,108,255,0.08);
      border-radius: 12px;
    }
  }
}

.btn-block {
  position: absolute;
  left: 0;
  bottom: 17px;
  width: 100%;
  display: flex;
  justify-content: center;
  padding: 0 16px;
  box-sizing: border-box;
}
</style>
